package com.stefanie.nettydemo.test2;

import com.stefanie.nettydemo.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:stefanie-zy
 * @time:2023/12/5-14:12
 * @description: 使用NIO理解阻塞模式
 */
public class Server {

    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(20);

        // 1-建立服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 2-创建监听端口
        ssc.bind(new InetSocketAddress(8888));

        // 3-连接集合
        List<SocketChannel> channelList = new ArrayList<>();
        while (true) {
            // 4-客户端连接
            SocketChannel sc = ssc.accept();
            channelList.add(sc);

            //5-接受该客户端发送的数据
            for (SocketChannel channel : channelList) {
                channel.read(buffer);
                buffer.flip();
                ByteBufferUtil.debugAll(buffer);
                buffer.clear();
            }
        }
    }
}
